全部文章
【React X Kotlin】用kotlin写react是什么味道
1.创建工程 然后用IntelliJ IDEA打开该工程,等待初始化完成 2.运行 3.尝下味道 实现一个列表 State setState 拓展方法 4.参考
1.创建工程
create-react-app my-app --scripts-version react-scripts-kotlin


然后用IntelliJ IDEA打开该工程,等待初始化完成
2.运行
yarn start

3.尝下味道
实现一个列表
class App : RComponent<RProps, RState>() {
override fun RBuilder.render() {
val list = arrayOf("一", "二", "三")
ul {
list.forEach { item ->
li {
+ item
}
}
}
}
}

State
interface AppState : RState{
var list: List<String>
}
class App : RComponent<RProps, AppState>() {
override fun AppState.init(){
list = listOf("一", "二", "三")
}
override fun RBuilder.render() {
ul {
state.list.forEach { item ->
li {
+ item
}
}
}
}
}
setState
interface AppState : RState {
var list: List<String>
var count: Int
}
class App : RComponent<RProps, AppState>() {
override fun AppState.init() {
list = listOf()
count = 0
}
override fun RBuilder.render() {
ul {
state.list.forEach { item ->
li {
+item
}
}
}
button {
+ "点击了${state.count}下"
setProp("onClick", {
setState {
count++
list += count.toString()
}
})
}
}
}

拓展方法
inline fun RDOMBuilder<kotlinx.html.Tag>.onClick(noinline method: () -> Unit) {
setProp("onClick", method)
}
button {
+ "点击了${state.count}下"
onClick {
setState {
count++
list += count.toString()
}
}
}

评论
4 条评论